package com.lcq.demo.common.job;

import com.lcq.demo.entity.po.ScheduleTask;
import com.lcq.demo.service.ScheduleTaskLogService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

@Component
public class ReflectionTaskExecutorJob implements Job {

    @Autowired
    private ApplicationContext applicationContext;

    @Resource
    private ScheduleTaskLogService scheduleTaskLogService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        ScheduleTask task = new ScheduleTask();
        Integer taskId = (Integer) jobExecutionContext.getMergedJobDataMap().get("taskId");
        String taskName = (String) jobExecutionContext.getMergedJobDataMap().get("taskName");
        String callTarget = (String) jobExecutionContext.getMergedJobDataMap().get("callTarget");
        task.setId(taskId);
        task.setTaskName(taskName);
        task.setCallTarget(callTarget);
        if (taskId == null) {
            throw new JobExecutionException("Task ID is NULL");
        }
        String[] split = callTarget.split("\\.");
        String methodName = split[split.length - 1];
        String className = callTarget.substring(0, callTarget.lastIndexOf("."));
        try {
            Class<?> clazz = Class.forName(className);
//            Object bean = applicationContext.getBean(clazz);
            Object object = clazz.getDeclaredConstructor().newInstance();
            Method method = clazz.getMethod(methodName, Integer.class);
            Date startTime = new Date();
            method.invoke(object, taskId);
            Date endTime = new Date();
            scheduleTaskLogService.logTaskExecution(task, 1, startTime, endTime);

        } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException |
                 InstantiationException e) {
            throw new JobExecutionException("Failed to execute task", e);
        }
    }
}
